package cn.minimelon.solon.service.system.impl;

import cn.hutool.core.collection.CollUtil;
import cn.minimelon.solon.domain.system.BaseCompanyInfo;
import cn.minimelon.solon.domain.system.CompanyInfoVO;
import cn.minimelon.solon.domain.system.ESQueryVO;
import cn.minimelon.solon.domain.system.EsToken;
import cn.minimelon.solon.mapper.system.CompanyInfoMapper;
import cn.minimelon.solon.service.system.BasCompanyInfoService;
import cn.minimelon.solon.utils.ElasticFactory;
import lombok.extern.slf4j.Slf4j;
import org.beetl.sql.core.query.LambdaQuery;
import org.beetl.sql.solon.annotation.Db;
import org.noear.esearchx.EsCommand;
import org.noear.esearchx.PriWw;
import org.noear.esearchx.model.EsData;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class BasCompanyInfoServiceImpl implements BasCompanyInfoService {
    @Db("master")
    private CompanyInfoMapper companyInfoMapper;

    @Override
    public Long initEsData() {
        long count = companyInfoMapper.allCount();
        int pageSize = (int) Math.ceil(count / 10000.0D);

        List<BaseCompanyInfo> list = null;
        for (int i = 0; i < pageSize; i++) {
            LambdaQuery<BaseCompanyInfo> query = companyInfoMapper.createLambdaQuery().limit(1, 10000).orderBy(BaseCompanyInfo::getId);
            if (i > 0 && list != null) {
                query.andGreat("id", list.get(list.size() - 1).getId());
            }
            list = query.select();
            if (CollUtil.isNotEmpty(list)) {
                log.info("第一条：{}", list.get(0));
                for (BaseCompanyInfo info : list) {
                    try {
                        ElasticFactory.getInstance().indice("bas_company_info").upsert(info.getId(), info);
                    } catch (IOException e) {
                        throw new RuntimeException("bas_company_info error");
                    }
                }
            }
        }
        return count;
    }

    @Override
    public List<CompanyInfoVO> queryEsData(ESQueryVO query) {
        try {
            EsData<CompanyInfoVO> result = ElasticFactory.getInstance().indice(query.getIndex())
                    .where(c -> c.match("cname", query.getText()))
                    .selectList(CompanyInfoVO.class);
            log.info("result: {}", ONode.stringify(result));
            return result.getList();
        } catch (Exception ex) {
            throw new RuntimeException(query.getIndex() + " error");
        }
    }

    @Override
    public List<EsToken> analyzeWord(ESQueryVO query) {
        try {
            EsCommand cmd = new EsCommand();
            cmd.method = PriWw.method_post;
            cmd.dslType = PriWw.mime_json;
            cmd.dsl = ONode.stringify(query);
            log.info("result: {}", cmd.dsl);
            cmd.path = "/_analyze";
            String json = ElasticFactory.getInstance().execAsBody(cmd);
            ONode tokens = ONode.loadStr(json).get("tokens");
            return tokens.toObjectList(EsToken.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}
